package com.wrupple.muba.common.client.activity;

import java.util.HashMap;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.inject.Provider;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.domain.DesktopPlace;
import com.wrupple.muba.common.shared.State.DesktopManager;
import com.wrupple.muba.desktop.client.module.ForkedActivity;

public class ForkedActivityDelegate implements ForkedActivity ,DesktopActivity{
	
	private Provider<? extends Activity> defaultActivity;
	private String distinctivePlacePropertyName;
	private HashMap<String,Activity> activities;
	private Activity lastActivity;
	private DesktopManager desktopmanager;

	public ForkedActivityDelegate(Provider<? extends Activity> defaultActivity,String distinctivePlacePropertyName,DesktopManager desktopmanager) {
		super();
		this.desktopmanager=desktopmanager;
		activities = new HashMap<String, Activity>();
		this.defaultActivity= defaultActivity;
		setDistinctivePlacePropertyName(distinctivePlacePropertyName);
	}

	@Override
	public String mayStop() {
		return lastActivity.mayStop();
	}

	@Override
	public void onCancel() {
		lastActivity.onCancel();
	}

	@Override
	public void onStop() {
		lastActivity.onStop();
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		init(desktopmanager.getWhere());
		lastActivity.start(panel, eventBus);
	}


	@Override
	public void setDistinctivePlacePropertyName(String name) {
		this.distinctivePlacePropertyName=name;
	}

	@Override
	public void registerActivity(String distinctivePlacePropertyValue, Activity activity) {
		activities.put(distinctivePlacePropertyValue, activity);
	}
	
	public Activity getActivityForPlace(DesktopPlace place){
		String distinctiveValue = place.getProperty(distinctivePlacePropertyName);
		Activity defaultActivity = getDefaultActivity() ;
		if(distinctiveValue==null){
			return defaultActivity;
		}else if(activities.containsKey(distinctiveValue)){
			Activity forked = activities.get(distinctiveValue);
			return forked;
		}else{
			return defaultActivity;
		}
	}


	public Activity getDefaultActivity() {
		return defaultActivity.get();
	}

	public String getDistinctivePlacePropertyName() {
		return distinctivePlacePropertyName;
	}

	
	private void init(DesktopPlace place) {
		Activity act = getActivityForPlace(place);
		lastActivity = act;
	}


	@Override
	public void getActivityProcess(DesktopPlace item, DataCallback<ActivityProcess> callback) {
		init(item);
		if(lastActivity instanceof DesktopActivity){
			((DesktopActivity) lastActivity).getActivityProcess(item, callback);
		}else{
			throw new IllegalArgumentException("Activity with distinctive value :"+item.getProperty(distinctivePlacePropertyName)+" is not sequential");
		}		
	}

}
